package com.elinshaw.netty4.config

import com.elinshaw.netty4.utils.Constant
import groovy.util.logging.Slf4j
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.handler.timeout.IdleState
import io.netty.handler.timeout.IdleStateEvent

/**
 * @author Administrator
 */
@Slf4j
class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {

    /** 空闲次数 */
    private int idleCount = 1

    /** 发送次数 */
    private int count = 1

    @Override
    void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt
            IdleState idleState = idleStateEvent.state()
            switch (idleState) {
                case IdleState.READER_IDLE:
                    log.info("READER_IDLE")
                    if (idleCount > 2) {
                        ctx.channel().close()
                    }
                    idleCount++
                    break
                case IdleState.WRITER_IDLE:
                    log.info("WRITER_IDLE")
                    break
                case IdleState.ALL_IDLE:
                    log.info("ALL_IDLE")
                    break
            }
        } else {
            super.userEventTriggered(ctx, evt)
        }
    }

    @Override
    void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("第{}次服务端接受的消息{}", count, msg)
        String message = (String) msg
        if (Constant.HEART_BEAT == message) {
            ctx.writeAndFlush(Constant.HEART_BEAT)
        }
        count++
    }

}
